<?php
$exmatid = $_POST['exmatid'];
require('../../cofd/common.php');
$stmt = $conn->prepare("SELECT * FROM exam_page WHERE exmatid = ?");
if ($stmt === false) {
    echo json_encode(array('status' => 500, 'msg' => '准备查询失败: ' . $mysqli->error));
    exit();
}
$stmt->bind_param('s', $exmatid); 
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $getresult = $row['linkshare'];
    }
} else {
    echo json_encode(array('status' => 500, 'msg' => '未找到相关数据'));
    exit();
}
function gennersjsczfcynn($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function anotersjfirest($conn){
    $randomstring = gennersjsczfcynn(8);
    $stmt = $conn->prepare("SELECT COUNT(*) FROM exam_page WHERE linkshare = ?");
    $stmt->bind_param("s", $randomstring);
    $stmt->execute();
    $result = $stmt->get_result(); 
    $exists = $result->fetch_array()[0]; 
    if ($exists == 0) {
        return $randomstring;
    }else{
        return anotersjfirest($conn);
    }
}
if($getresult == ''){
    $getstess = anotersjfirest($conn);
    $stmt = $conn->prepare("UPDATE exam_page SET linkshare = ? WHERE exmatid = ?");
    $stmt->bind_param('ss', $getstess, $exmatid); 
    if ($stmt->execute()) {
        echo json_encode(array('status' => 200, 'msg' => $getstess));
    } else {
        echo json_encode(array('status' => 400, 'msg' => '操作失败'));
    }
}else{
    echo json_encode(array('status' => 200, 'msg' => $getresult));
}
$stmt->close();
$conn->close();
?>